package com.angus.modules.content.controller.common;
import com.angus.common.core.utils.StringUtils;
import com.angus.common.core.utils.file.FileTypeUtils;
import com.angus.common.core.utils.file.MimeTypeUtils;
import org.springframework.beans.factory.annotation.Value;
import com.angus.common.core.web.controller.BaseController;
import com.angus.common.core.web.domain.AjaxResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

@RestController
@RequestMapping("/upload")
public class UploadController extends BaseController {

    @Value("${image.upload.dir}")
    private String uploadDir;

    @Value("${image.spring.servlet.multipart.max-file-size}")
    private String maxFileSizeMB;

    @PostMapping("/store")
    public AjaxResult store(MultipartFile file) throws IOException {
        if (file.isEmpty()){
            return AjaxResult.warn("请选择要上传的文件");
        }
        String extension = FileTypeUtils.getExtension(file);
        if (!StringUtils.equalsAnyIgnoreCase(extension, MimeTypeUtils.IMAGE_EXTENSION)) {
            return AjaxResult.warn("文件格式不正确，请上传" + Arrays.toString(MimeTypeUtils.IMAGE_EXTENSION) + "格式的图片");
        }
        // 大小限制
        int maxFileSize = Integer.parseInt(maxFileSizeMB.replaceAll("MB",""));
        long maxFileSizeBytes = convertMBToBytes(maxFileSize);
        if (file.getSize() > maxFileSizeBytes) {
            return AjaxResult.warn("文件大小不能超过"+maxFileSizeMB);
        }

        // 确保上传目录存在（自动创建）
        Path uploadPath = Paths.get(uploadDir).toAbsolutePath();
        Files.createDirectories(uploadPath);

        // 生成安全文件名（避免覆盖）
        String fileName = UUID.randomUUID() + "." + extension;
        Path targetPath = uploadPath.resolve(fileName);

        // 保存文件（直接写入宿主机挂载目录）
        file.transferTo(targetPath);

        Map<String, String> data = new HashMap<>();
        data.put("url",fileName); // 前端访问路径
        data.put("filename", file.getOriginalFilename());
        data.put("size", String.valueOf(file.getSize()));

        logger.info("upload resp: {}", data);

        return AjaxResult.success(data);
    }

    public static long convertMBToBytes(int mb) {
        return (long) mb * 1024 * 1024;
    }
}
